<template>
  <!-- 回访任务查询 -->
  <div class="visitTaskSearch">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
          <el-form-item prop="objectMethod" label="客户生成方式">
            <el-select v-model="formData.objectMethod" placeholder="请选择客户生成方式" @change="methodChange">
              <el-option label="导入数据" :value="0" />
              <el-option label="线上电商" :value="1" />
              <el-option label="线下门店" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item prop="groupId" label="所属业务组">
            <SearchSelectPicker
              url="/call-center/api/v1/businessGroup/page"
              placeholder="请选择所属业务组"
              lable-name="groupName"
              :value.sync="formData.groupId"
              :cur-options.sync="groupOption"
              multiple
              collapse-tags
              @selectChange="()=>{formData.customerService=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="customerService" label="执行坐席">
            <!-- :params="{query:{groupNo:{value:groupOption.map(e=>e.groupNo),operator:'in'}},type:0}" -->
            <SearchSelectPicker
              ref="customerServiceSelect"
              url="/call-center/api/v1/staffInfo/page"
              :other-raw="{groupNos:groupOption.map(e=>e.groupNo)}"
              placeholder="请选择执行坐席"
              value-name="accountNo"
              lable-name="staffName"
              :parent-id="formData.groupId"
              :value.sync="formData.customerService"
              :lable.sync="accountName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="taskType" label="任务类型">
            <SearchSelectPicker
              url="/call-center/api/v1/callBackTask/type/page"
              placeholder="请选择任务类型"
              lable-name="typeName"
              :value.sync="formData.taskType"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="taskId" label="任务名称">
            <SearchSelectPicker
              ref="taskIdSelect"
              url="/call-center/api/v1/callBackTask/taskManage"
              placeholder="任务名称"
              :params="{query:{objectMethod:formData.objectMethod},type:0}"
              :parent-id="formData.objectMethod"
              lable-name="taskName"
              :value.sync="formData.taskId"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="state" label="执行状态">
            <el-select v-model="formData.state" placeholder="请选择执行状态" clearable filterable>
              <el-option
                v-for="(option,index) in stateOptions"
                :key="index"
                :label="option.dictName"
                :value="option.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===2" prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              method="get"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              :value.sync="formData.officeCode"
              @selectChange="()=>{formData.disCode=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===2" prop="agent" label="经销商">
            <SearchSelectPicker
              ref="disSelect"
              :disabled="!formData.officeCode"
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :must-pid="true"
              :parent-id="formData.officeCode"
              :value.sync="formData.disCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item
            v-if="formData.objectMethod===1"
            prop="platformName"
            label="电商平台"
          >
            <SearchSelectPicker
              url="/select-service/api/v1/eco/platform/page"
              :params="{query:null,type:0}"
              placeholder="请选择电商平台"
              value-name="code"
              lable-name="name"
              :value.sync="formData.platformCode"
              @selectChange="()=>{formData.shopCode=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item
            v-if="formData.objectMethod===1"
            prop="shopName"
            label="电商店铺"
          >
            <SearchSelectPicker
              ref="storeSelect"
              url="/select-service/api/v1/eco/shop/page"
              placeholder="请选择电商店铺"
              :params="{query:{platformCode:formData.platformCode},type:0}"
              value-name="code"
              lable-name="name"
              :parent-id="formData.platformCode"
              :value.sync="formData.shopCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="customerName" label="客户姓名">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable />
          </el-form-item>
          <el-form-item prop="customerPhone" label="联系电话">
            <el-input v-model="formData.customerPhone" placeholder="请输入联系电话" clearable />
          </el-form-item>
          <template v-if="formData.objectMethod===0">
            <el-form-item prop="remarks1" label="备注信息1">
              <el-input v-model="formData.remarks1" placeholder="请输入备注信息" clearable />
            </el-form-item>
            <el-form-item prop="remarks2" label="备注信息2">
              <el-input v-model="formData.remarks2" placeholder="请输入备注信息" clearable />
            </el-form-item>
            <el-form-item prop="remarks3" label="备注信息3">
              <el-input v-model="formData.remarks3" placeholder="请输入备注信息" clearable />
            </el-form-item>
            <el-form-item prop="remarks4" label="备注信息4">
              <el-input v-model="formData.remarks4" placeholder="请输入备注信息" clearable />
            </el-form-item>
            <el-form-item prop="remarks5" label="备注信息5">
              <el-input v-model="formData.remarks5" placeholder="请输入备注信息" clearable />
            </el-form-item>
          </template>
          <el-form-item prop="date" :span="7" label="任务执行周期">
            <el-date-picker
              v-model="formData.date"
              type="daterange"
              range-separator="-"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item :span="5" label-width="79px">
            <Button @click="()=>{$refs.form.resetFields();accountName = $store.state.user.userCache.staffName}">重置</Button>
            <Button type="primary" :loading="loading" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Button
          type="primary"
          @click="implement"
        >执行</Button>
        <Seats :selected-arry="selectedAry" :object-method="formData.objectMethod" @refresh="refresh('onPage')"></Seats>
      </div>
      <table-box
        :key="tableBoxKey"
        ref="table"
        no-request
        :other-filters="otherFilters"
        :table-config="tableConfig"
        @data-change="getTableData"
        @selection-change="selectionChange"
      >
        <!-- :selected-arry.sync="selectedAry" -->
        <el-table-column slot="before" type="selection" align="center" width="50"></el-table-column>
        <!-- <template v-if="tableType===0">
          <el-table-column prop="remarks1" label="备注1"></el-table-column>
          <el-table-column prop="remarks2" label="备注2"></el-table-column>
          <el-table-column prop="remarks3" label="备注3"></el-table-column>
          <el-table-column prop="remarks4" label="备注4"></el-table-column>
          <el-table-column prop="remarks5" label="备注5"></el-table-column>
        </template> -->
        <!-- <el-table-column v-if="tableType!==0" prop="orderCode" label="订单编号" width="230"></el-table-column> -->
        <el-table-column label="执行状态">
          <template slot-scope="scope">
            <span>{{ getStateLabel(scope.row.state) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customerServiceName" label="执行坐席" width="130">
          <template slot-scope="scope">
            <span>{{ getSeatsTable(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回访时间" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.startDate && scope.row.endDate">{{ scope.row.startDate }} 至 {{ scope.row.endDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="callBackRemark" label="回访备注" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="回访结果" width="110">
          <template slot-scope="scope">
            <Button v-if="scope.row.state===6" type="primary" @click="detail(scope.row)">查看详情</Button>
          </template>
        </el-table-column>
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import Seats from './child/seats'
import { ccDict } from '@/api/dataDict'
import { filtersRaw, addOneDay } from '@/utils'
export default {
  name: 'VisitTaskSearch',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    SearchSelectPicker,
    Seats
  },
  data() {
    return {
      groupOption: [], // 当前选择的业务组
      tableBoxKey: 'tableBoxKey', // table-box组件设置key
      problemLen: 0,
      tableType: 0,
      otherFilters: [], // 查询条件参数（处理后)
      selectedAry: [],
      tableList: [], // 表格数据
      accountName: '',
      formData: {
        objectMethod: 2,
        buyChannel: 1,
        date: [],
        groupId: [],
        disCode: '',
        shopCode: '',
        customerService: ''
      },
      formRules: {
        objectMethod: [{ required: true, message: '请选择客户生成方式', trigger: 'change' }]
      },
      loading: false,
      stateOptions: [],
      tableConfig: {
        interfacePath: '',
        sort: 'createTime',
        order: 'desc',
        pageFlag: true,
        hideFuncBar: true,
        tablePage: [10, 20, 30, 50, 100, 200, 300, 500, 1000],
        // 表格字段动态配置
        setting: []
      },
      // base
      setting: [
        {
          prop: 'taskName',
          label: '任务名称',
          minWidth: 100
        },
        {
          prop: 'typeName',
          label: '任务类型',
          minWidth: 100
        },
        {
          prop: 'customerName',
          label: '客户姓名',
          minWidth: 100
        },
        {
          prop: 'customerPhone',
          label: '联系电话',
          minWidth: 100
        }
      ],
      // 备注
      remarksList: [
        {
          prop: 'remarks1',
          label: '备注1',
          minWidth: 120
        },
        {
          prop: 'remarks2',
          label: '备注2',
          minWidth: 120
        },
        {
          prop: 'remarks3',
          label: '备注3',
          minWidth: 120
        },
        {
          prop: 'remarks4',
          label: '备注4',
          minWidth: 120
        },
        {
          prop: 'remarks5',
          label: '备注5',
          minWidth: 120
        }
      ],
      // 订单
      order: [
        {
          prop: 'orderCode',
          label: '订单编号',
          minWidth: '200'
        }
      ],
      // ...
      last: [
        // {
        //   prop: 'state',
        //   width: 120,
        //   label: '执行状态',
        //   propEnum: {
        //     domainCode: 'marketing',
        //     appCode: 'call-center',
        //     dictTypeCode: 'STATE'
        //   }
        // },
        // {
        //   prop: 'customerServiceName',
        //   label: '执行坐席',
        //   width: 120
        // }
      ]
    }
  },
  computed: {
    canImplement() {
      if (this.selectedAry.length) {
        if (this.selectedAry[0].state === 6) {
          return false
        } else {
          return true
        }
      } else {
        return false
      }
    }
  },
  beforeMount() {
    this.accountName = this.$store.state.user.userCache.staffName
    this.formData.customerService = this.$store.state.user.userCache.accountNo
  },
  created() {
    if (this.$isShop()) {
      this.$set(this.formData, 'objectMethod', 1)
    }
  },
  mounted() {
    ccDict('STATE').then(res => {
      this.stateOptions = res.data
    })
    this.methodChange(this.formData.objectMethod || 0)
  },
  methods: {
    // 客户生成方式改变
    methodChange(v) {
      this.tableType = v
      const setting = [...this.setting]
      if (v === 0) {
        setting.push(...this.remarksList)
      } else {
        setting.push(...this.order)
      }
      setting.push(...this.last)
      this.$set(this.tableConfig, 'setting', setting)
      this.$set(this.formData, 'taskId', '')
      this.$set(this.formData, 'date', [])
      this.$refs.form.clearValidate()
      this.tableBoxKey = (Math.random() * 0xfffffff).toString(16)
    },
    // 根据条件查询
    queryHandle() {
      const list = []
      // =
      const commonEq = ['customerService', 'taskType', 'taskId', 'state']
      const clientEq = ['platformCode', 'shopCode']
      const reEq = ['officeCode', 'disCode']
      // like
      const commonLike = ['customerName', 'customerPhone']
      const exportLike = ['remarks1', 'remarks2', 'remarks3', 'remarks4', 'remarks5']
      // in
      const commonIn = ['groupId']
      for (const [key, value] of Object.entries(this.formData)) {
        if (value === '' || value === null || value === undefined || key === 'objectMethod' || (value instanceof Array && value.length <= 0)) {
          continue
        }
        if (value instanceof Array && value.length > 0) {
          if (key === 'date') {
            list.push(filtersRaw('startDate', value[0], '>='))
            list.push(filtersRaw('endDate', addOneDay(value[1]), '<='))
          }
          if (commonIn.includes(key)) {
            list.push(filtersRaw(key, `[${value.join(',')}]`, 'in'))
          }
        } else {
          // 公共有参数groupId、customerService、taskType、taskId、state、customerName、customerPhone
          if (commonEq.includes(key)) {
            list.push(filtersRaw(key, value, '='))
          }
          if (commonLike.includes(key)) {
            list.push(filtersRaw(key, value, 'like'))
          }
          // 导入数据
          if (this.formData.objectMethod === 0) {
            if (exportLike.includes(key)) {
              list.push(filtersRaw(key, value, 'like'))
            }
          }
          // 电商数据
          if (this.formData.objectMethod === 1) {
            if (clientEq.includes(key)) {
              list.push(filtersRaw(key, value, '='))
            }
          }
          // 零售数据
          if (this.formData.objectMethod === 2) {
            if (reEq.includes(key)) {
              list.push(filtersRaw(key, value, '='))
            }
          }
        }
      }

      this.otherFilters = list
      if (this.formData.objectMethod === 0) {
        // 数据导入任务查询
        this.tableConfig.interfacePath =
          '/call-center/api/v1/callBackTask/import/page'
      } else if (this.formData.objectMethod === 2) {
        // 线下任务查询
        this.tableConfig.interfacePath =
            '/call-center/api/v1/callBackTask/offline/page'
      } else {
        // 线上任务查询
        this.tableConfig.interfacePath =
            '/call-center/api/v1/callBackTask/online/page'
      }
      this.refresh()
    },
    refresh(onPage) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(onPage)
      })
    },
    // 查看详情
    detail(row) {
      const type = this.formData.objectMethod.toString()
      this.$router.push({
        name: 'TaskHandle',
        query: { taskType: type, id: row.id }
      })
    },
    // 执行
    implement() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请先选择要执行的任务！')
      }
      if (this.selectedAry[0].state === 6) {
        return this.$message.info('该任务已回访完成！')
      }
      // 为每一次的查询条件缓存数据
      const key = (Math.ceil(Math.random() * 0xfffffffffff)).toString(16)
      const list = this.tableList.map(e => {
        return e.id
      })

      const type = this.formData.objectMethod.toString()
      sessionStorage.setItem(key, JSON.stringify({ currentId: this.selectedAry[0].id, list }))
      this.$router.push({
        path: '/callBackTask/taskHandle',
        query: { taskType: type, type: '1', key }
      })
    },
    selectionChange(val) {
      this.selectedAry = val
    },
    // 表格数据改变
    getTableData(val) {
      this.tableList = val.data.records.filter((e) => {
        if (e.state !== 6) {
          return e
        } else {
          return false
        }
      })
      this.tableType = this.formData.objectMethod
    },
    // 获取状态名称
    getStateLabel(val) {
      const item = this.stateOptions.find(e => {
        return e.dictCode === (val + '')
      })
      return item ? item.dictName : ''
    },
    getSeatsTable(row) {
      if (row.customerService) {
        return row.customerServiceName + '(' + row.customerService + ')'
      }
    }
  }
}
</script>
<style lang='scss'>
.visitTaskSearch{
  tr{
    background: white !important;
  }
}
</style>
